package com.bitejiuyeke.forum.services.impl;

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.dao.ArticleMapper;
import com.bitejiuyeke.forum.exception.ApplicationException;
import com.bitejiuyeke.forum.model.Article;
import com.bitejiuyeke.forum.model.Board;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IArticleService;
import com.bitejiuyeke.forum.services.IBoradService;
import com.bitejiuyeke.forum.services.IUserService;
import com.bitejiuyeke.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-12-04
 * Time: 22:56
 */
@Slf4j
@Service

public class ArticleServiceImpl implements IArticleService {
    @Resource
    ArticleMapper articleMapper;
    @Resource
    IUserService userService;
    @Resource
    IBoradService boardService;
    @Override
    public void create(Article article) {
    //非空校验
        if(article == null || article.getUserId()==null || StringUtil.isEmpty(article.getTitle()) || article.getBoardId() == null || StringUtil.isEmpty(article.getContent())){
    log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
    throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
       article.setLikeCount(0);//点赞数
        article.setVisitCount(0);//访问数
        article.setReplyCount(0);//回复数
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //加入数据库
        int articleRow = articleMapper.insertSelective(article);
        if(articleRow<=0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));

        }
        //更新用户帖数量
        User user = userService.selectById(article.getUserId());
        if(user == null){
            log.warn(ResultCode.FAILED_CREATE.toString()+",发帖失败，userid = "+ article.getUserId());
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
//更新用户发帖数
        userService.addOneArticleCountById(user.getId());
        Board board = boardService.selectById(article.getBoardId());
        if(board == null){
            log.warn(ResultCode.FAILED_CREATE.toString()+",发帖失败，board id = "+ article.getBoardId());
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //更新板块中的帖子数量
        boardService.addOneArticleCountById(board.getId());
        // 打印日志
        log.info( ResultCode.SUCCESS.toString()+"发帖成功，userid = "
                + article.getUserId()+",board id = "+ article.getBoardId()+" 帖子id" + article.getId());

    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 非空校验
        if (boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
           throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString()+",board id = "+ boardId+" 不存在");
        throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //调用dao查询
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
if(id == null || id <= 0) {
    log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
    throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
}
        Article article = articleMapper.selectDetailById(id);
if(article == null){
    log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
    throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
}
//更新帖子访问数
Article updateArticle = new Article();
updateArticle.setId(article.getId() );
updateArticle.setVisitCount(article.getVisitCount()+1);

//保存到数据库
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(i!=1){
log.warn(ResultCode.ERROR_SERVICES.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新返回对象的访问次数
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    @Override
    public Article selectById(Long id) {
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if(id == null || id <= 0  || StringUtil.isEmpty(title)|| StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        //构建要更新的帖子
        Article updateArticle = new Article();
        updateArticle.setId(id);  //id
        updateArticle.setTitle(title);  //标题
        updateArticle.setContent(content);   //内容
        updateArticle.setUpdateTime(new Date());  //更新时间
        //调用dao
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if(id == null || id <= 0 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState()==1 ){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(id);  //id
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        //调用dao
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        //非空校验
        if(id == null || id <= 0 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据id，获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState()==1 ){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString()+"Article id: "+id);
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
          //调用dao
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
       //更新板块中的帖子数
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功，article id: "+article.getId()+ " user id: "+article.getUserId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if(id == null || id <= 0 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子记录
        Article article = articleMapper.selectByPrimaryKey(id);

        if(article == null ||  article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString()+"Article id: "+id);
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        //原回复数加1
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        //更新帖子记录
        int update = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(update != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空检验
        if(userId == null || userId <= 0 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
      //校验用户是否存在
        User user = userService.selectById(userId);
        if(user == null ){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"User id: "+userId);
            throw   new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用dao
        List<Article> articles = articleMapper.selectByUserId(userId);

        return articles;
    }
}
